package net.yxsoft.service.infrastructure;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.sun.corba.se.spi.presentation.rmi.IDLNameTranslator;
import net.yxsoft.kit.CustomDb;
import net.yxsoft.kit.Helper;
import net.yxsoft.model.infrastructure.*;
import rapid.jfinal.BaseService;
import rapid.core.Authuser;

import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Leo on 2016/5/13.
 */
public class RoleService extends BaseService {

  public static final RoleService INSTANCE = new RoleService();

  /**
  * @MethodName: checkMenus
  * @Description: 根据角色返回菜单权限
  * @param: roleId 角色主键
  * @return * @return java.lang.String
  * @throws
  * @date 2023/8/31 13:27
  * @author wj
  */
  public String checkMenus(String roleId) {
    List<String> ids = new ArrayList<String>();
    List<TsPermission> pers = TsPermission.dao.find("select p.* from TS_PERMISSION p inner join TS_MENU M on p.MENU_ID = M.ID " + "inner join TS_ROLE R on p.ROLE_ID = R.ID where r.ID = ?", roleId);
    for(TsPermission per : pers) {
      ids.add(per.getMenuId().toString());
    }

    String[] strs = ids.toArray(new String[ids.size()]);
    return StrKit.join(strs, ",");
  }

  /**
  * @MethodName: saveRole
  * @Description: 保存组信息
  * @param: role
   * @param: user
  * @return * @return int
  * @throws
  * @date 2023/8/31 13:28
  * @author wj
  */
  public int saveRole(TsRole role, Authuser user) {
    boolean result = false;
    if(StrKit.notNull(user)) {
      Date date = new Date(System.currentTimeMillis());
      String userId = user.getId();
      String userNam = user.getName();

      if(role.getId() == null) {
        if(TsRole.dao.find("SELECT 1 FROM TS_ROLE WHERE CODE = ? ", role.getCode()).size() > 0) {
          return -1; //code重复
        }
        if(TsGroup.dao.find("SELECT 1 FROM TS_ROLE WHERE  NAME = ?",  role.getName()).size() > 0) {
          return -2; //code重复
        }
        role.setId(Helper.bulidUUID());
        role.setCreatorId(userId.toString());
        role.setCreatorName(userNam);
        role.setCreateTime(date);
        role.setEditorId(userId.toString());
        role.setEditorName(userNam);
        role.setUpdateTime(date);
        role.setFormdataTopCheck(role.getFormdataTopCheck());

        result = role.save();
      } else {
        if(TsRole.dao.find("SELECT 1 FROM TS_ROLE WHERE CODE = ? ", role.getCode()).size() > 0) {
          return -1; //code重复
        }
        if(TsGroup.dao.find("SELECT 1 FROM TS_ROLE WHERE  NAME = ?",  role.getName()).size() > 0) {
          return -2; //code重复
        }


        TsRole tsRole = TsRole.dao.findById(role.getId());

        tsRole.set("NAME", role.getName());
        tsRole.set("CODE", role.getCode());
        tsRole.set("ENABLED", role.getEnabled());
        tsRole.set("LOCKED", role.getLocked());
        tsRole.set("NOTE", role.getNote());
        tsRole.set("EDITOR_ID", userId);
        tsRole.set("EDITOR_NAME", userNam);
        tsRole.set("UPDATE_TIME", date);
        tsRole.setFormdataTopCheck(role.getFormdataTopCheck());

        result = tsRole.update();
      }
    }

    return 0;
  }

  /**
  * @MethodName: deleteRoleById
  * @Description: 根据主键删除角色
  * @param: id 主键
  * @return * @return boolean
  * @throws
  * @date 2023/8/31 13:28
  * @author wj
  */
  public boolean deleteRoleById(String id) throws SQLException {
    boolean result = false;
    if(StrKit.notBlank(id)) {
      try {
        deleteRelatedTerms(id);
        result = true;
      } catch(SQLException e) {
        throw e;
      }
    }

    return result;
  }

  /**
  * @MethodName: deleteRoles
  * @Description: 根据主键集合删除角色
  * @param: ids 主键集合
  * @return * @return boolean
  * @throws
  * @date 2023/8/31 13:28
  * @author wj
  */
  @Before(Tx.class)
  public boolean deleteRoles(String[] ids) throws SQLException {
    boolean result = false;

    if(ids.length > 0) {
      try {
        for(String id : ids) {
          deleteRelatedTerms(id);
        }
        result = true;
      } catch(SQLException e) {
        throw e;
      }
    }

    return result;
  }

  /**
  * @MethodName: saveRolePermissions
  * @Description: 保存角色的菜单权限
  * @param: roleId 角色主键
   * @param: menuIds 菜单主键集合
  * @return * @return boolean
  * @throws
  * @date 2023/8/31 13:29
  * @author wj
  */
  @Before(Tx.class)
  public boolean saveRolePermissions(String roleId, String[] menuIds) throws SQLException {
    boolean result = false;
    int i = (int) CustomDb.updateWithExceptionHandling("delete from TS_PERMISSION where ROLE_ID = ?", roleId).getData();

    for(String menuId : menuIds) {
      result = new TsPermission().set("ROLE_ID", roleId).set("MENU_ID", menuId).save();
      if(!result) {
        throw new SQLException();
      }
    }

    return result;
  }

  /**
  * @MethodName: deleteRelatedTerms
  * @Description: 删除菜单子项和关联项
  * @param: roleId
  * @return * @return void
  * @throws
  * @date 2023/8/31 13:29
  * @author wj
  */
  private void deleteRelatedTerms(String roleId) throws SQLException {
    try {
      List<TsUrRelation> urs = TsUrRelation.dao.find("SELECT * FROM TS_UR_RELATION WHERE ROLE_ID = ?", roleId);
      if(urs.size() > 0) {
        for(TsUrRelation tsUrRelation : urs) {
          tsUrRelation.delete();
        }
      }

      List<TsPermission> pers = TsPermission.dao.find("SELECT * FROM TS_PERMISSION WHERE ROLE_ID = ?", roleId);
      if(pers.size() > 0) {
        for(TsPermission tsPermission : pers) {
          tsPermission.delete();
        }
      }

      TsRole.dao.deleteById(roleId);
      List<TsRole> roles = TsRole.dao.find("SELECT ID FROM TS_ROLE WHERE PID = ?", roleId);

      if(roles.size() > 0) {
        for(TsRole tsRole : roles) {
          deleteRelatedTerms(tsRole.getId().toString());
        }
      }
    } catch(SQLException e) {
      throw e;
    }
  }

  /**
  * @MethodName: getAllRoleInfo
  * @Description:  获取全部角色信息
  * @param:
  * @return * @return java.util.List<net.yxsoft.model.infrastructure.TsRole>
  * @throws
  * @date 2023/8/31 13:29
  * @author wj
  */
  public List<TsRole> getAllRoleInfo() {
    List<TsRole> _rolelist = TsRole.dao.find("SELECT * FROM TS_ROLE ORDER BY NAME");
    return _rolelist;
  }

  /**
  * @MethodName: getWhether
  * @Description: 数据字典查询数据 动态表单全数据
  * @param:
  * @return * @return java.util.List<net.yxsoft.model.infrastructure.TsCode>
  * @throws
  * @date 2023/8/31 13:30
  * @author wj
  */
  public List<TsCode> getWhether(){
    List<TsCode> list = new TsCode().dao().find("select CUSTOMID,CODENAME from TS_CODE where CODETYPE = 'WHETHER' and LEAF = 2");
    return list;
  }
}
